<?php
declare (strict_types=1);

namespace app;

use think\App;
use think\Request;
use think\Validate;
use app\admin\model\PageModule as pm;
use app\admin\model\Module;
use think\exception\ValidateException;


/**
 * API控制器基类
 */
abstract class ApibaseController
{
	
    /**
     * Request实例
     * @var Request
     */
    protected Request $request;

    /**
     * 是否批量验证
     * @var bool
     */
    protected bool $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected array $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(protected App $app)
    {
        $this->request                 = $this->app->request;
        $this->request->controllerPath = str_replace('.', '/', $this->request->controller(true));
        $this->Apiresponse = '';
        // 控制器初始化

        $this->initialize();
    }



    /**
     * 控制器初始化方法
     * @access protected
     * @throws Throwable
     */
    protected function initialize()
    {
        $this->request->filter('filter');
    }

    /**
     * 公共空方法
     * @access public
     * @param string $method func_name
     * @param array $args arguments
     * @return string|array
     */
    public function __call(string $method, array $args)
    {
          return $this->index();
    }

    /**
     * 公共 index 方法
     * @access public
     * @return string
     */
    public function index()
    {   
        // 输出模块返回的数据
        return $this->fetch();
    }


    /**
     * 渲染数据输出 json返回
     * @access protected
     * @param  string $template 模板文件名或者内容 route
     * @param  array  $vars     模板输出变量
     * @return mixed
     */
    protected function fetch(string $template = '', array $vars = [])
    {
        $vars = $vars ?: $this->load();
        return json($vars);
    }


    protected function load($module = 'api'): array
    {    // 获取传参
        $method = $this->request->method();
        $args = $this->request->param();
        $url = $this->request->url();
        $url = str_replace("/index.php","",$url);
        $w = [];
        $w['p.shop_id'] = $this->request->shop_id;
        $page_module = [];
        if(isset($args['path'])){
               $w['a.path'] = $args['path'];
               $find = pm::alias("p")->join("page_path a","p.page_id=a.id","LEFT")->where($w)->find();
        }else{
              $w['p.api_url'] = $url;
              $w['p.type'] = 1;
              $find = pm::alias("p")->where($w)->find();
        }
        if(empty($find['methods'])){
               return ['code'=>100,'msg'=>'无效请求'];
        }
 
        if($method == 'GET' || $method == 'POST'){
              $method_arr = explode(",",$find['methods']);
              $me = ['GET'=>1,'POST'=>2];
              if(!in_array($me[$method],$method_arr)){
                  return ['code'=>100,'msg'=>'无效请求!'];
              }
        }else{
            return ['code'=>100,'msg'=>'Invalid request!'];
        }
        
         if($find){
              if(empty($find['page_module_ids'])){
                  return ['code'=>100,'msg'=>'未绑定模块！'];
              }
              $modules = Module::whereIn("id",explode(",",$find['page_module_ids']))->field("class,method")->select();
              foreach($modules as &$v){
                   $page_module[] = $v['class'].".".$v['method'];
              }
         }else{
              return ['code'=>100,'msg'=>'无模块匹配！'];
         }
 

        if(empty($page_module)){
              return ['code'=>100,'msg'=>'无效请求'];
        }
        $args['shop_id'] = $this->request->shop_id;
        $args['uid'] = $this->request->uid;
        $args['ip'] = $this->request->ip();
        $appLogic      = new \app\common\AppLogic($module);
        $ret = $appLogic->run($page_module, $args , '');
        return $ret;
    }



}